﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Data;
using System.Collections;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.ComponentModel;
using BLL.Entities;

namespace BLL
{

    /// <summary>
    /// Enum for the end status of the CSV creation
    /// </summary>
    public enum ECSVCreateEndStatus
    {
        /// <summary>
        /// Successfully
        /// </summary>
        CSVCreatedSuccess,
        /// <summary>
        /// General Error
        /// </summary>
        CSVCreatedGeneralError,
        /// <summary>
        /// File read/write error
        /// </summary>
        CSVCreatedFileReadWriteError,
        /// <summary>
        /// Creation canceled
        /// </summary>
        CSVCreatedCancelProcess
    }

    /// <summary>
    /// Class for holding a worker thread and all the methods for creating a CSV file from Data rows.
    /// the worker thread in the this class will work in an asynchrony manner and raise an event when finished creating the file
    /// </summary>
    public class CSVCreator
    {
        #region Constants

        private const string CSV_EXTENSION = ".csv";
        private const string COL_DELIMITER = ",";
        private const string SPACE_CHARACTER = " ";
        private const string BACKSLASH = "\"";

        #endregion


        const string NAME = "Name";
        const string START_DATE = "Start Date";
        const string END_DATE = "End Date";
        const string VISIT_AT = "Visit At";


        public void ExportShiftsToCSV(Dictionary<GymWorker, List<Shift>> shifts, string fullPath)
        {
            List<string> columns = new List<string>() { NAME, START_DATE, END_DATE };
            List<RowData> rows = new List<RowData>();
            foreach (var shift in shifts)
            {
                foreach (var sh in shift.Value)
                {
                    RowData row = new RowData();
                    row.Data.Add(shift.Key.FirstName);
                    row.Data.Add(sh.StartingHour.ToString());
                    row.Data.Add(sh.EndingHour.ToString());
                    rows.Add(row);
                }
            }
            CreateCSVFile(columns, rows, fullPath);
        }

        public void ExportVisitsToCSV(Dictionary<Trainee, List<GymVisit>> visits, string fullPath)
        {
            List<string> columns = new List<string>() { NAME, VISIT_AT };
            List<RowData> rows = new List<RowData>();
            foreach (var visit in visits)
            {
                foreach (var vis in visit.Value)
                {
                    RowData row = new RowData();
                    row.Data.Add(visit.Key.FullName);
                    row.Data.Add(vis.Start.ToString());
                    rows.Add(row);
                }
            }
            CreateCSVFile(columns, rows, fullPath);
        }

        

        private static void CreateCSVFile(List<string> columns, List<RowData> rows, string fullPath)
        {
            StringBuilder stringBuilder = new StringBuilder();
            //Append all columns titles to the string builder
            foreach (var item in columns)
            {
                stringBuilder.Append(item);
                stringBuilder.Append(COL_DELIMITER);
            }

            // remove last comma separator and add newline
            stringBuilder = stringBuilder.Remove(stringBuilder.Length - 1, 1);
            stringBuilder.Append(Environment.NewLine.ToString());

            foreach (RowData row in rows)
            {
                foreach (var cell in row.Data)
                {
                    string addString = cell.Replace(BACKSLASH, BACKSLASH + BACKSLASH);
                    addString = BACKSLASH + addString + BACKSLASH;

                    stringBuilder.Append(addString);
                    stringBuilder.Append(COL_DELIMITER);
                }

                // remove last comma separator and add newline
                stringBuilder = stringBuilder.Remove(stringBuilder.Length - 1, 1);
                stringBuilder.Append(Environment.NewLine.ToString());
            }

            //Write the string builder to a .csv file
            WriteToFile(stringBuilder, fullPath);
        }

        /// <summary>
        /// Method helper for writing the string builder to the file
        /// </summary>
        /// <param name="stringBuilder">the string in a CSV format</param>
        private static void WriteToFile(StringBuilder stringBuilder, string fullPath)
        {
            string errMsg;
            try
            {
                WriteToFile(fullPath, stringBuilder.ToString());
            }
            catch (IOException ex)
            {
                errMsg = string.Format("CSVCreator->WriteToFile Method faield.\r\n{0}", ex.ToString());
            }
            catch (Exception ex)
            {
                errMsg = string.Format("CSVCreator->WriteToFile Method faield.\r\n{0}", ex.ToString());
            }
        }

        /// <summary>
        /// Writes to file.
        /// </summary>
        /// <param name="fullFileName">Full name and path of the file.</param>
        /// <param name="data">The contnet.</param>
        private static void WriteToFile(string fullFileName, string data)
        {
            using (FileStream fileStream = File.Create(fullFileName))
            {
                using (StreamWriter streamWriter = new StreamWriter(fileStream))
                {
                    streamWriter.Write(data);
                    streamWriter.Close();
                }
            }
        }
    }
}

